package com.weilive.push.service.apns;

import java.util.List;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.notnoop.apns.APNS;
import com.notnoop.apns.ApnsService;
import com.notnoop.apns.PayloadBuilder;
import com.weilive.core.utils.FileUtils;
import com.weilive.push.ServerContext;

public class ApnsPusher {
	private static final Logger logger = LoggerFactory.getLogger(ApnsPusher.class);

	// 发送
	private static ApnsService service = ServerContext.isWorkingEnv()
			? APNS.newService().asPool(Runtime.getRuntime().availableProcessors() * 2)
					.withCert(FileUtils.getResourcePath(ServerContext.getApnsProd()), "12677484")
					.withProductionDestination().withDelegate(new ApnsDelegateImpl()).build()
			: APNS.newService().asPool(Runtime.getRuntime().availableProcessors() * 2)
					.withCert(FileUtils.getResourcePath(ServerContext.getApnsDev()), "12677484")
					.withSandboxDestination().withDelegate(new ApnsDelegateImpl()).build();

	/**
	 * 
	 * 
	 * @param token
	 * @param badge
	 *            推送次数
	 * @param msg
	 * @param trId
	 * @param roomUserId
	 * @throws Exception
	 */
	public static void APNSPush(String token, String msg, Long userId) throws Exception {

		Set<String> inactiveTokens = ApnsInactiveDevice.getInactiveDevices();

		if (inactiveTokens.contains(token)) {
			return;
		}
		PayloadBuilder pb = APNS.newPayload();
		String payload = pb.alertBody(msg).customField("userId", String.valueOf(userId))
				.customField("messageType", "live").badge(1).sound("default").build();

		service.push(token, payload);
	}

	/**
	 * 
	 * 
	 * @param tokens
	 * @param badge
	 *            推送次数
	 * @param msg
	 * @param trId
	 * @param roomUserId
	 * @throws Exception
	 */
	public static void APNSPush(List<String> tokens, String msg, Long userId) throws Exception {

		Set<String> inactiveTokens = ApnsInactiveDevice.getInactiveDevices();

		tokens.removeAll(inactiveTokens);

		PayloadBuilder pb = APNS.newPayload();
		String payload = pb.alertBody(msg).customField("userId", String.valueOf(userId))
				.customField("messageType", "live").badge(1).sound("default").build();

		service.push(tokens, payload);

		logger.warn("IOS推送完成=" + tokens.size());
	}
}
